package com.ruoyi.web.controller.pic;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.VO.DdtPicVO;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.domain.DdtPic;
import com.ruoyi.service.pic.IDdtPicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;

/**
 * 图片资源明细Controller
 * 
 * @author 张书林
 * @date 2025-06-22
 */
@RestController
@RequestMapping("/pic/pic")
@Slf4j
public class DdtPicController extends BaseController
{
    @Autowired
    private IDdtPicService ddtPicService;

    private static final String UPLOAD_PATH = "https://abiaoqing.com";

    /**
     * 查询图片资源明细列表
     */
    @GetMapping("/list")
    public TableDataInfo list(DdtPic ddtPic)
    {
        startPage();
        List<DdtPic> list = ddtPicService.selectDdtPicList(ddtPic);
        return getDataTable(list);
    }

    /**
     * 导出图片资源明细列表
     */
    @Log(title = "图片资源明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DdtPic ddtPic)
    {
        List<DdtPic> list = ddtPicService.selectDdtPicList(ddtPic);
        ExcelUtil<DdtPic> util = new ExcelUtil<DdtPic>(DdtPic.class);
        util.exportExcel(response, list, "图片资源明细数据");
    }

    /**
     * 获取图片资源明细详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(ddtPicService.selectDdtPicById(id));
    }

    /**
     * 新增图片资源明细
     */
    @PostMapping
    public AjaxResult add(@RequestBody DdtPicVO ddtPicVO) {
        try {
            List<DdtPic> savedPics = new ArrayList<>();
            List<String> picUrlList = ddtPicVO.getPicUrlList();
            if(CollUtil.isNotEmpty(picUrlList)){
                for (String picUrl : picUrlList) {
                    DdtPic ddtPic = new DdtPic();
                    ddtPic.setPicUrl(picUrl);
                    ddtPic.setType(ddtPicVO.getType());
                    ddtPic.setCreatedAt(DateUtil.date());
                    ddtPic.setUpdatedAt(DateUtil.date());
                    savedPics.add(ddtPic);
                }
            }
            if(CollUtil.isNotEmpty(savedPics)){
                ddtPicService.inserList(savedPics);
            }
            return AjaxResult.success("上传成功", savedPics);
        } catch (Exception e) {
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }

    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) {
        try {
            String picUrl = "";
            if (!file.isEmpty()) {
                // 处理文件存储和设置其他属性
                picUrl = storeFile(file); // 自定义文件存储方法
            }
            return AjaxResult.success("上传成功", picUrl);
        } catch (Exception e) {
            return AjaxResult.error("上传失败: " + e.getMessage());
        }
    }

    // 文件存储方法示例
    private String storeFile(MultipartFile file) throws IOException {
        String suffix = "." + FileUtil.getSuffix(file.getOriginalFilename());
        String fileName = IdUtil.simpleUUID() + suffix;
        log.info("上传的图片资源为：{}",fileName);
        // 自定义存储逻辑，例如：
        String uploadDir = "/work/images/";
        Path uploadPath = Paths.get(uploadDir);
        if (!Files.exists(uploadPath)) {
            Files.createDirectories(uploadPath);
        }
        Path filePath = uploadPath.resolve(fileName);
        log.info("上传路径为：{}",filePath);
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);
        return UPLOAD_PATH + filePath;
    }

    /**
     * 修改图片资源明细
     */
    @Log(title = "图片资源明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DdtPicVO ddtPicVO)
    {
        return toAjax(ddtPicService.updateDdtPic(ddtPicVO));
    }

    /**
     * 删除图片资源明细
     */
    @Log(title = "图片资源明细", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids,
                             @RequestParam("picUrl") String picUrl)
    {
        return toAjax(ddtPicService.deleteDdtPicByIds(ids,picUrl));
    }
}
